<?php

namespace app\admin\model\detection;

use think\Model;


class Lists extends Model
{

    

    

    // 表名
    protected $name = 'detection';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;
    protected $type = [
        'json'    =>  'json',
    ];

    // 追加属性
    protected $append = [
        'status_text',
        'applytime_text',
        'json_text'
    ];
    

    
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }

    public function getJsonTextAttr($value, $data)
    {
        $value = $value ?: (isset($data['json'] ) && $data['json'] ? json_decode($data['json'],true) : '');

        if(is_array($value) && !empty($value)){
            $vehicle_type = [];
            foreach ($value as $json)
            {
                $category_name = db('category')->where('id', $json['vehicle_type'])->value('name');
                if($category_name)
                    $vehicle_type[] = $category_name;
            }
            $value = !empty($vehicle_type) ? $vehicle_type : '';
        }
        return $value;
    }

    public function getTypeList()
    {
        return ['1' => __('Type 1'), '2' => __('Type 2'), '3' => __('Type 3')];
    }

    public function getApplytimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['applytime'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setApplytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function admin()
    {
        return $this->belongsTo('app\admin\model\Admin', 'admin_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
